package cn.com.dhcc.app.pub.core.util.settlement.compute;

import cn.com.dhcc.app.pub.core.util.settlement.compute.filter.MD5Filter;
import cn.com.dhcc.app.pub.core.util.settlement.compute.store.*;
import cn.com.dhcc.app.pub.core.util.settlement.compute.task.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 结算工具类
 * @日期 2016-8-9上午9:22:48
 * @作者 张洪涛
 * @版权所有:东华软件
 * @版本: 1.0
 */
public class SettUtil {
	/**
	 * 发送到交换平台后临时文件落地
	 * @param table 表名  schema.table
	 * @param datas 数据，主键hash集合
	 * @param taskLogId 
	 */
	private static ExecutorService executor = Executors.newSingleThreadExecutor();
	private static DataGroupHandler groupHandler = new DefaultDataGroupHandler();
	private static DataProcessHandler processHandler = new DefaultDataProcessHandler();
	public static void dataStore(String table,List<String> datas,String taskLogId){
		groupHandler.addFilter(new MD5Filter());
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put(table, datas);// 表
		executor.submit(new DataStoreTask(taskLogId, map, groupHandler,processHandler)); 
	}
	/**
	 * 发送成功后，集合合并
	 * @param taskid 任务id
	 * @param taskLogId 任务日志id
	 */
	public static void dataMerge(String taskid,String taskLogId,Date date){
		executor.submit(new DataMergeTask(taskLogId,taskid,date, processHandler));
	}
	/**
	 * 删除数据
	 * @param taskLogId 任务日志id
	 */
	public static void dataDelete(String taskLogId){
		executor.submit(new DataDeleteTask(taskLogId, processHandler));
	}
	/**
	 * 结算
	 * @param taskId 任务id
	 * @param table 表名
	 * @param datas 结算数据
	 * @param taskLogId 任务id
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static int dataCompute(String taskId,String table,List<String> datas,String taskLogId,Date date) throws InterruptedException, ExecutionException{
		groupHandler.addFilter(new MD5Filter());
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put(table, datas);// 表
		int sum = executor.submit(new DataComputeTask(taskId, taskLogId, map, date,groupHandler, processHandler)).get();
		return sum;
	}
	/**
	 * 取计算结果
	 * @param taskId 结算任务的id
	 * @param tableName
	 * @param date
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static List<String> dataComputeResult(String taskId, String table, Date date) throws InterruptedException, ExecutionException{
		ComputeResultVo data = executor.submit(new DataComputeResultTask(taskId, table, date, processHandler)).get();
		return data.getSrcList();
	}
}
